#include"../stream/inputfilestream.h"
#include"../stream/outputfilestream.h"
#include"../sort/dWayMerge_class.h"
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cstdio>
#include<string>

using namespace std;

int main(int argc, char *argv[])
{
	if(argc!=3)
	{
		std::cout << "usage is : " << argv[0] << " [num] [size]" << std::endl;
		exit(0);
	}

	int num = atoi(argv[1]);
	int size = atoi(argv[2]);
	int count = 1;
	dWayMerge d;
	Element e;
	
	if(!d.heapIntialize(num))
	{
		std::cout << "failed to allocate memory";
	}
	outputfilestream os[num];
	outputfilestream dway;
	dway.create("dWayFileStream.txt");
        for(int i=0;i<num;i++)
        {
                stringstream ss;
                ss << i;
                os[i].create(ss.str().c_str());
                for(int j=0;j<size;j++)
                        os[i].write_s((size-j));
		os[i].close_s();
        }
	
        inputfilestream is[num];
	inputfilestream output;
        for(int i=0;i<num;i++)
        {
                stringstream ss;
                ss << i;
                is[i].open_s(ss.str().c_str());
		int a = is[i].read_next();
		if(a != EOF)
                {
                        e.data = a;
                        e.index = i;
                        d.heapInsert(e);
                }
                else
                    break;

        }
	/*
	for(int i=0;i<num;i++)
        {
                int a = is[i].read_next();
                if(a != EOF)
		{
			e.data = a;
			e.index = i;
			d.heapInsert(e);
		}
                else
                    break;
        }
	*/
	int counter = size*(num);
	int a;
	while(counter)
	{
	if(!d.heapIsEmpty())
	{
		e = d.heapRemoveMax();
		cout << " max :: value: " << e.data << " index: " << e.index << std::endl;
       		dway.write_s(e.data);
		counter--;
	}
	a = is[e.index].read_next();
	if(a!=EOF)
	{
		e.data = a;
		d.heapInsert(e);
	}
	}

	dway.close_s();
	std::cout << std::endl;
	counter = size*num;
	output.open_s("dWayFileStream.txt");
	while(counter)
	{
	cout << output.read_next() << '\t';
	counter--;
	}

	std::cout << std::endl;

}

